<template>
  <div class="chat-container">
    <!-- 创建新对话按钮 -->
    <button class="new-chat-icon" @click="startNewChat">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
        <path fill-rule="evenodd" d="M12 3.75a.75.75 0 01.75.75v6.75h6.75a.75.75 0 010 1.5h-6.75v6.75a.75.75 0 01-1.5 0v-6.75H4.5a.75.75 0 010-1.5h6.75V4.5a.75.75 0 01.75-.75z" clip-rule="evenodd" />
      </svg>
      <span class="tooltip">新对话</span>
    </button>
    
    <!-- 聊天区域 -->
    <div class="chat-main" :class="{ 'history-open': showHistory }">
      <!-- 聊天消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div v-if="messages.length === 0" class="welcome-container">
          <div class="welcome-content">
            <h2>AI助手</h2>
            <p>您可以向我询问任何问题，我会尽力帮助您解决问题。</p>
            <div class="suggestion-chips">
              <button class="suggestion-chip" @click="useQuestion('如何查看系统监控信息？')">
                如何查看系统监控信息？
              </button>
              <button class="suggestion-chip" @click="useQuestion('怎样优化系统性能？')">
                怎样优化系统性能？
              </button>
              <button class="suggestion-chip" @click="useQuestion('如何使用终端命令？')">
                如何使用终端命令？
              </button>
            </div>
          </div>
        </div>
        
        <div v-for="(message, index) in messages" :key="index" 
          :class="['message', message.role === 'user' ? 'user-message' : 'assistant-message']">
          <template v-if="message.role === 'assistant'">
            <div class="message-avatar">
              <span class="avatar assistant-avatar">AI</span>
            </div>
            <div class="message-content">
              <div v-if="isLoading && message.content === ''" class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
              <div v-else v-html="formatMessage(message.content)"></div>
            </div>
          </template>
          <template v-else>
            <div class="message-content">
              <div v-html="formatMessage(message.content)"></div>
            </div>
            <div class="message-avatar">
              <span class="avatar user-avatar">用户</span>
            </div>
          </template>
        </div>
      </div>
      
      <!-- 底部输入框 -->
      <div class="chat-input-container">
        <div class="chat-input-wrapper">
          <textarea 
            ref="inputElement"
            v-model="userInput" 
            placeholder="输入消息..." 
            @keydown.enter.prevent="handleEnterKey"
            @input="autoResizeTextarea"
            rows="1"
            class="chat-input"
          ></textarea>
          <button 
            class="send-button" 
            @click="sendMessage" 
            :disabled="!userInput.trim() || isLoading"
            :class="{ 'send-button-active': userInput.trim() }"
          >
            <svg v-if="!isLoading" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6">
              <path d="M3.478 2.405a.75.75 0 00-.926.94l2.432 7.905H13.5a.75.75 0 010 1.5H4.984l-2.432 7.905a.75.75 0 00.926.94 60.519 60.519 0 0018.445-8.986.75.75 0 000-1.218A60.517 60.517 0 003.478 2.405z" />
            </svg>
            <span v-else class="loading-icon"></span>
          </button>
        </div>
        <div class="input-info">
          按 Enter 发送消息，Shift + Enter 换行
        </div>
      </div>
    </div>
    
    <!-- 历史记录侧边栏 -->
    <div class="chat-history" :class="{ 'history-open': showHistory }">
      <div class="history-header">
        <h3>对话历史</h3>
      </div>
      <div class="history-list">
        <div v-if="chatHistory.length === 0" class="no-history">
          暂无历史对话
        </div>
        <div 
          v-for="(chat, index) in chatHistory" 
          :key="index" 
          class="history-item"
          :class="{ 'active': currentChatId === chat.id }"
          @click="loadChat(chat.id)"
        >
          <div class="history-item-title">{{ chat.title || '新对话' }}</div>
          <div class="history-item-date">{{ formatDate(chat.date) }}</div>
        </div>
      </div>
    </div>
    
    <!-- 切换历史按钮 -->
    <button class="toggle-history-btn" @click="toggleHistory">
      <svg v-if="!showHistory" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6">
        <path fill-rule="evenodd" d="M11.03 3.97a.75.75 0 010 1.06l-6.22 6.22H21a.75.75 0 010 1.5H4.81l6.22 6.22a.75.75 0 11-1.06 1.06l-7.5-7.5a.75.75 0 010-1.06l7.5-7.5a.75.75 0 011.06 0z" clip-rule="evenodd" />
      </svg>
      <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6">
        <path fill-rule="evenodd" d="M12.97 3.97a.75.75 0 011.06 0l7.5 7.5a.75.75 0 010 1.06l-7.5 7.5a.75.75 0 11-1.06-1.06l6.22-6.22H3a.75.75 0 010-1.5h16.19l-6.22-6.22a.75.75 0 010-1.06z" clip-rule="evenodd" />
      </svg>
    </button>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, onBeforeUnmount } from 'vue';
import { marked } from 'marked';
import * as echarts from 'echarts';

// 配置marked
marked.use({
  gfm: true,
  breaks: true,
  pedantic: false,
  silent: false,
  highlight: function(code, lang) {
    return code;
  }
});

// 自定义渲染器，用于处理特殊的图表标记
const renderer = new marked.Renderer();
const originalCodeRenderer = renderer.code.bind(renderer);

// 重写code渲染器，处理图表标记
renderer.code = function(code, language, isEscaped) {
  // 检查是否为图表代码块
  if (language === 'chart' || language === 'echarts') {
    // 为图表生成唯一ID
    const chartId = 'chart-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
    
    // 返回带有图表容器的HTML - 使用转义处理script标签
    return `<div class="ai-chart-container">
              <div id="${chartId}" class="ai-chart"></div>
              <${'script'} class="chart-data" type="application/json" data-chart-id="${chartId}">
                ${code}
              </${'script'}>
            </div>`;
  }
  
  // 对于非图表代码块，使用原始渲染器
  return originalCodeRenderer(code, language, isEscaped);
};

// 更新marked配置，使用自定义渲染器
marked.use({ renderer });

// WebSocket连接
const ws = ref(null);
const wsConnected = ref(false);
const streamingMessage = ref('');

// 聊天状态
const userInput = ref('');
const messages = ref([]);
const isLoading = ref(false);
const messagesContainer = ref(null);
const inputElement = ref(null);

// 历史记录相关
const showHistory = ref(false);
const chatHistory = ref([]);
const currentChatId = ref(null);

// 图表实例管理
const chartInstances = ref({});

// 初始化WebSocket连接
const initWebSocket = () => {
  try {
    // 实际使用时替换为真实的WebSocket地址
    const wsUrl = 'ws://localhost:8000/api/chat/ws';
    
    // 创建WebSocket连接
    ws.value = new WebSocket(wsUrl);
    
    // 连接建立时的处理
    ws.value.onopen = () => {
      console.log('WebSocket连接已建立');
      wsConnected.value = true;
    };
    
    // 接收消息的处理
    ws.value.onmessage = (event) => {
      handleWebSocketMessage(event.data);
    };
    
    // 连接关闭时的处理
    ws.value.onclose = () => {
      console.log('WebSocket连接已关闭');
      wsConnected.value = false;
      // 可以在这里添加重连逻辑
    };
    
    // 连接错误时的处理
    ws.value.onerror = (error) => {
      console.error('WebSocket连接错误:', error);
      wsConnected.value = false;
    };
  } catch (error) {
    console.error('初始化WebSocket失败:', error);
  }
};

  // 处理WebSocket接收的消息
const handleWebSocketMessage = (data) => {
  try {
    // 解析收到的JSON数据
    const message = JSON.parse(data);
    
    // 根据消息类型处理
    switch (message.type) {
      case 'connection_success': // 连接成功
        console.log('WebSocket连接成功:', message.content);
        break;
        
      case 'stream': // 流式响应
        // 累加流式文本
        streamingMessage.value += message.content;
        
        // 寻找空的助手消息
        const emptyStreamMessage = messages.value.find(msg => msg.role === 'assistant' && msg.content === '');
        
        // 如果找到空的助手消息，更新它
        if (emptyStreamMessage) {
          emptyStreamMessage.content = streamingMessage.value;
        } else {
          // 检查是否有任何助手消息
          const assistantMessages = messages.value.filter(msg => msg.role === 'assistant');
          if (assistantMessages.length > 0) {
            // 如果有助手消息，更新最后一条
            assistantMessages[assistantMessages.length - 1].content = streamingMessage.value;
          } else {
            // 如果没有助手消息，创建一个新的
            console.warn('没有找到助手消息，创建新消息');
            messages.value.push({
              role: 'assistant',
              content: streamingMessage.value
            });
          }
        }
        break;
        
      case 'end': // 流式响应结束
        // 结束加载状态
        isLoading.value = false;
        streamingMessage.value = '';
        break;
        
      case 'error': // 错误消息
        console.error('AI回复错误:', message.content);
        isLoading.value = false;
        
        // 查找是否已经有一个空的助手消息可以更新
        const emptyAssistantMessage = messages.value.find(msg => msg.role === 'assistant' && msg.content === '');
        if (emptyAssistantMessage) {
          // 更新已有的空消息
          emptyAssistantMessage.content = `抱歉，我遇到了一些问题: ${message.content}`;
        } else {
          // 查找最后一条助手消息
          const assistantMessages = messages.value.filter(msg => msg.role === 'assistant');
          if (assistantMessages.length > 0) {
            // 更新最后一条助手消息
            assistantMessages[assistantMessages.length - 1].content = `抱歉，我遇到了一些问题: ${message.content}`;
          } else {
            // 添加新的错误消息
            messages.value.push({
              role: 'assistant',
              content: `抱歉，我遇到了一些问题: ${message.content}`
            });
          }
        }
        
        streamingMessage.value = '';
        break;
        
      case 'history_list': // 历史对话列表
        console.log('收到历史对话列表:', message.content);
        if (message.content && message.content.length > 0) {
          chatHistory.value = message.content;
        } else {
          chatHistory.value = [];
        }
        break;
        
      case 'history_data': // 单个对话的历史消息
        console.log('收到对话历史消息:', message.content);
        if (message.content && message.content.messages) {
          // 设置当前对话ID
          currentChatId.value = message.content.id;
          // 加载历史消息
          messages.value = message.content.messages;
        }
        break;
        
      case 'get_history': // 处理get_history类型的消息
        console.log('收到get_history类型消息，忽略处理');
        break;
        
      default:
        console.log('收到未知类型的消息:', message);
        // 不在界面显示未知类型的消息
    }
  } catch (error) {
    console.error('处理WebSocket消息失败:', error);
  }
};

// 发送WebSocket消息
const sendWebSocketMessage = (message) => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    console.log('发送WebSocket消息:', message);
    ws.value.send(JSON.stringify(message));
  } else {
    console.error('WebSocket未连接，无法发送消息');
    // 可以在这里添加重连逻辑
  }
};

// 处理Enter键
const handleEnterKey = (e) => {
  // Shift+Enter 换行，单独Enter发送
  if (!e.shiftKey) {
    sendMessage();
  }
};

// 自动调整文本域高度
const autoResizeTextarea = () => {
  const textarea = inputElement.value;
  if (!textarea) return;
  
  // 重置高度
  textarea.style.height = 'auto';
  
  // 计算新高度
  const newHeight = Math.min(textarea.scrollHeight, 150);
  textarea.style.height = `${newHeight}px`;
};

// 格式化消息内容（支持Markdown和图表）
const formatMessage = (content) => {
  return marked.parse(content);
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  
  const now = new Date();
  const messageDate = new Date(date);
  
  // 今天的消息显示时间
  if (messageDate.toDateString() === now.toDateString()) {
    return messageDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }
  
  // 昨天的消息
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (messageDate.toDateString() === yesterday.toDateString()) {
    return '昨天';
  }
  
  // 其他日期显示完整日期
  return messageDate.toLocaleDateString();
};

// 切换历史记录面板
const toggleHistory = () => {
  showHistory.value = !showHistory.value;
  
  // 当打开历史面板时，才请求历史对话列表
  if (showHistory.value && wsConnected.value) {
    sendWebSocketMessage({
      type: 'get_history'
    });
  }
};

// 加载指定对话
const loadChat = (chatId) => {
  // TODO: 从后端加载指定ID的对话
  console.log('加载对话:', chatId);
  currentChatId.value = chatId;
  
  // 清空当前消息，准备加载历史消息
  messages.value = [];
  
  // 通过WebSocket发送获取历史对话的请求
  if (wsConnected.value) {
    sendWebSocketMessage({
      type: 'get_history',
      conversation_id: chatId
    });
  } else {
    console.error('WebSocket未连接，无法加载历史对话');
  }
};

// 开始新对话
const startNewChat = () => {
  messages.value = [];
  currentChatId.value = null;
  if (inputElement.value) {
    inputElement.value.focus();
  }
};

// 使用建议问题
const useQuestion = (question) => {
  userInput.value = question;
  sendMessage();
};

// 初始化图表
const initCharts = () => {
  // 查找所有图表脚本标签
  nextTick(() => {
    const chartScripts = document.querySelectorAll('.chart-data');
    
    chartScripts.forEach(script => {
      const chartId = script.getAttribute('data-chart-id');
      const chartContainer = document.getElementById(chartId);
      
      // 如果容器存在且还没有初始化过
      if (chartContainer && !chartInstances.value[chartId]) {
        try {
          // 解析图表配置
          const chartConfig = JSON.parse(script.textContent);
          
          // 初始化ECharts实例
          const chartInstance = echarts.init(chartContainer);
          chartInstance.setOption(chartConfig);
          
          // 保存实例引用
          chartInstances.value[chartId] = chartInstance;
          
          // 添加窗口大小变化时的自适应
          window.addEventListener('resize', () => {
            chartInstance.resize();
          });
        } catch (error) {
          console.error('初始化图表失败:', error);
          chartContainer.innerHTML = `<div class="chart-error">图表加载失败: ${error.message}</div>`;
        }
      }
    });
  });
};

// 监听消息变化，自动滚动到底部并初始化图表
watch(messages, () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
    // 初始化新的图表
    initCharts();
  });
}, { deep: true });

// 组件销毁前清理图表实例
onBeforeUnmount(() => {
  if (ws.value) {
    ws.value.close();
    ws.value = null;
  }
  
  // 销毁所有图表实例
  Object.values(chartInstances.value).forEach(chart => {
    chart.dispose();
  });
  chartInstances.value = {};
});

// 初始化组件并加载历史对话
onMounted(() => {
  console.log('AIChat组件挂载');
  
  // 自动聚焦输入框
  if (inputElement.value) {
    inputElement.value.focus();
  }
  
  // 初始化WebSocket连接
  console.log('初始化WebSocket连接');
  initWebSocket();
  
  // 移除自动获取历史对话的监听
  // 不再自动获取历史对话
});

// 消息发送处理
const sendMessage = async () => {
  const input = userInput.value.trim();
  if (!input || isLoading.value) return;
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: input
  });
  
  // 清空输入框
  userInput.value = '';
  
  // 调整输入框高度
  autoResizeTextarea();
  
  // 显示加载状态
  isLoading.value = true;
  
  try {
    // 查找是否已有空的助手消息
    const existingEmptyMessage = messages.value.find(msg => msg.role === 'assistant' && msg.content === '');
    
    if (!existingEmptyMessage) {
      // 只有在没有空的助手消息时才添加
      console.log('添加空的助手消息，准备接收回复');
      messages.value.push({
        role: 'assistant',
        content: ''
      });
    } else {
      console.log('已存在空的助手消息，不再添加新的');
    }
    
    // 使用WebSocket发送消息
    if (wsConnected.value) {
      console.log('使用WebSocket发送消息');
      
      // 发送消息到WebSocket
      sendWebSocketMessage({
        type: 'message',
        content: input,
        conversation_id: currentChatId.value || null
      });
      
      // 如果是新对话，创建历史记录
      if (messages.value.length === 2 && !currentChatId.value) {
        const newChatId = Date.now().toString();
        currentChatId.value = newChatId;
        chatHistory.value.unshift({
          id: newChatId,
          title: input.length > 20 ? input.substring(0, 20) + '...' : input,
          date: new Date()
        });
      }
    } else {
      // WebSocket未连接，显示错误消息
      console.error('WebSocket未连接，无法发送消息');
      isLoading.value = false;
      
      // 更新已添加的空消息，提示用户连接错误
      const lastMessage = messages.value[messages.value.length - 1];
      if (lastMessage && lastMessage.role === 'assistant') {
        lastMessage.content = '抱歉，WebSocket连接已断开，无法与服务器通信。请刷新页面重试。';
      }
    }
  } catch (error) {
    console.error('AI回复出错:', error);
    isLoading.value = false;
    
    // 检查最后一条消息是否为空的助手消息
    const lastMessage = messages.value[messages.value.length - 1];
    if (lastMessage && lastMessage.role === 'assistant' && lastMessage.content === '') {
      // 更新已有的空消息
      lastMessage.content = '抱歉，我遇到了一些问题，无法回复您的消息。请稍后再试。';
    } else {
      // 添加新的错误消息
      messages.value.push({
        role: 'assistant',
        content: '抱歉，我遇到了一些问题，无法回复您的消息。请稍后再试。'
      });
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100%;
  position: relative;
  overflow: hidden;
  background-color: #ffffff;
  border-radius: 0;
  box-shadow: none;
  width: 100%;
}

/* 主聊天区域 */
.chat-main {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  transition: margin-right 0.3s ease;
  width: 100%;
  background: linear-gradient(to bottom, #f9fafc, #ffffff);
}

.chat-main.history-open {
  margin-right: 320px;
}

/* 消息容器 */
.messages-container {
  flex-grow: 1;
  overflow-y: auto;
  padding: 2rem;
  display: flex;
  flex-direction: column;
  gap: 2rem;
  scroll-behavior: smooth;
  background-image: linear-gradient(to bottom, rgba(240, 245, 255, 0.5), rgba(255, 255, 255, 0.8));
  padding-right: 4rem; /* 增加右侧内边距，为历史按钮留出空间 */
}

/* 消息样式 */
.message {
  display: flex;
  margin-bottom: 0.5rem;
  animation: fade-in 0.3s ease;
  max-width: 80%; /* 从85%减小到80%，防止重叠 */
  align-items: flex-start;
  position: relative; /* 添加相对定位 */
  z-index: 1; /* 确保消息在历史按钮下方 */
}

@keyframes fade-in {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.user-message {
  justify-content: flex-end;
  align-self: flex-end;
  margin-right: 10px; /* 添加右侧边距 */
  max-width: 75%; /* 进一步减小用户消息的最大宽度 */
}

.assistant-message {
  justify-content: flex-start;
  align-self: flex-start;
}

.message-avatar {
  margin: 0 10px;
  flex-shrink: 0;
}

.avatar {
  width: 42px;
  height: 42px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.12);
  transition: all 0.3s;
  border: 2px solid #fff;
}

.message:hover .avatar {
  transform: scale(1.08) rotate(5deg);
}

.user-avatar {
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: white;
}

.assistant-avatar {
  background: linear-gradient(135deg, #52c41a, #389e0d);
  color: white;
}

.message-content {
  max-width: 80%;
  padding: 16px 20px;
  border-radius: 16px;
  font-size: 15px;
  line-height: 1.6;
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
}

.message:hover .message-content {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.user-message .message-content {
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: white;
  border-top-left-radius: 16px;
  border-top-right-radius: 4px;
  border-bottom-left-radius: 16px;
  border-bottom-right-radius: 16px;
}

.user-message .message-content::before {
  content: none;
}

.assistant-message .message-content {
  background-color: #f5f7fa;
  color: #333;
  border-left: 3px solid #52c41a;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  border-bottom-left-radius: 16px;
  border-bottom-right-radius: 4px;
}

.assistant-message .message-content::before {
  content: none;
}

/* 输入框区域 */
.chat-input-container {
  padding: 1.25rem;
  border-top: 1px solid #f0f0f0;
  background-color: #fff;
}

.chat-input-wrapper {
  display: flex;
  align-items: flex-end;
  background-color: #f5f7fa;
  border-radius: 24px;
  padding: 12px 20px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.chat-input-wrapper:focus-within {
  box-shadow: 0 4px 20px rgba(24, 144, 255, 0.15);
  border-color: rgba(24, 144, 255, 0.3);
  background-color: #fff;
}

.chat-input {
  flex-grow: 1;
  border: none;
  outline: none;
  background: transparent;
  resize: none;
  max-height: 150px;
  font-size: 15px;
  line-height: 1.6;
  padding: 8px 0;
  overflow-y: auto;
}

.send-button {
  margin-left: 12px;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: #e6f7ff;
  color: #1890ff;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.send-button-active {
  background-color: #1890ff;
  color: white;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
}

.send-button:hover {
  transform: translateY(-2px) rotate(-10deg);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.45);
}

.send-button-active:hover {
  background-color: #40a9ff;
}

.send-button:disabled {
  background-color: #f5f5f5;
  color: #d9d9d9;
  box-shadow: none;
  cursor: not-allowed;
  transform: none;
}

.send-button svg {
  width: 20px;
  height: 20px;
}

.input-info {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin-top: 10px;
  font-style: italic;
}

/* 欢迎信息 */
.welcome-container {
  flex-grow: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: #666;
  padding: 2rem;
}

.welcome-content {
  max-width: 600px;
  background: linear-gradient(135deg, #f9fafc, #f0f5ff);
  padding: 2.5rem;
  border-radius: 20px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
  animation: welcome-fade-in 0.8s ease;
  border: 1px solid rgba(24, 144, 255, 0.1);
}

@keyframes welcome-fade-in {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.welcome-content h2 {
  font-size: 2.4rem;
  margin-bottom: 1.5rem;
  color: #1890ff;
  font-weight: 700;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.welcome-content p {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 2rem;
  color: #555;
}

.suggestion-chips {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  margin-top: 1.5rem;
}

.suggestion-chip {
  background-color: white;
  border: 1px solid #e6f7ff;
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.1);
}

.suggestion-chip:hover {
  background-color: #e6f7ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

/* 历史记录侧边栏 */
.chat-history {
  position: absolute;
  top: 0;
  right: 0;
  width: 320px;
  height: 100%;
  background-color: #f5f7fa;
  transform: translateX(100%);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border-left: 1px solid #eaedf1;
  display: flex;
  flex-direction: column;
  box-shadow: none;
}

.chat-history.history-open {
  transform: translateX(0);
  box-shadow: -4px 0 16px rgba(0, 0, 0, 0.1);
}

.history-header {
  padding: 1.25rem;
  border-bottom: 1px solid #eaedf1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
}

.history-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}



.new-chat-btn:hover {
  background-color: #40a9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(24, 144, 255, 0.35);
}

.new-chat-btn svg {
  width: 16px;
  height: 16px;
}

.history-list {
  flex-grow: 1;
  overflow-y: auto;
  padding: 1rem;
}

.no-history {
  text-align: center;
  color: #999;
  padding: 2rem 1rem;
  font-style: italic;
}

.history-item {
  padding: 1rem;
  border-radius: 10px;
  margin-bottom: 0.75rem;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background-color: #e6f7ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.history-item.active {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.history-item-title {
  font-size: 14px;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
  color: #333;
}

.history-item-date {
  font-size: 12px;
  color: #999;
}

/* 历史切换按钮 */
.toggle-history-btn {
  position: absolute;
  top: 1.5rem;
  right: 1.5rem;
  width: 42px;
  height: 42px;
  border-radius: 50%;
  background-color: #ffffff;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 200; /* 增加z-index确保在消息上方 */
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
}

.toggle-history-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.history-open .toggle-history-btn {
  right: 330px;
}

.toggle-history-btn svg {
  width: 20px;
  height: 20px;
  color: #1890ff;
}

/* 输入指示器动画 */
.typing-indicator {
  display: flex;
  align-items: center;
  padding: 12px 0;
  min-height: 24px;
}

.typing-indicator span {
  height: 10px;
  width: 10px;
  margin: 0 3px;
  background-color: #52c41a;
  border-radius: 50%;
  display: inline-block;
  opacity: 0.7;
}

.typing-indicator span:nth-child(1) {
  animation: bounce 1.2s infinite ease-in-out;
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation: bounce 1.2s infinite ease-in-out;
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation: bounce 1.2s infinite ease-in-out;
  animation-delay: 0.4s;
}

@keyframes bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-8px);
  }
}

/* 加载图标 */
.loading-icon {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 增强 Markdown 渲染样式 */
.message-content :deep(p) {
  margin: 0.75em 0;
}

.message-content :deep(pre) {
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  padding: 8px 12px;
  overflow-x: auto;
  margin: 8px 0;
}

.assistant-message .message-content :deep(pre) {
  background-color: rgba(0, 0, 0, 0.08);
}

.user-message .message-content :deep(pre) {
  background-color: rgba(255, 255, 255, 0.15);
}

.message-content :deep(code) {
  font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
  padding: 2px 5px;
  border-radius: 3px;
  font-size: 13px;
}

.assistant-message .message-content :deep(code):not(pre code) {
  background-color: rgba(0, 0, 0, 0.06);
}

.user-message .message-content :deep(code):not(pre code) {
  background-color: rgba(255, 255, 255, 0.15);
}

.message-content :deep(ul), .message-content :deep(ol) {
  margin: 0.75em 0;
  padding-left: 1.5em;
}

.message-content :deep(li) {
  margin: 0.3em 0;
}

.message-content :deep(a) {
  text-decoration: none;
}

.assistant-message .message-content :deep(a) {
  color: #1890ff;
}

.user-message .message-content :deep(a) {
  color: #e6f7ff;
  text-decoration: underline;
}

.message-content :deep(blockquote) {
  border-left: 3px solid;
  margin: 0.75em 0;
  padding-left: 12px;
}

.assistant-message .message-content :deep(blockquote) {
  border-left-color: #d9d9d9;
  background-color: rgba(0, 0, 0, 0.02);
  padding: 8px 12px;
  border-radius: 0 4px 4px 0;
}

.user-message .message-content :deep(blockquote) {
  border-left-color: rgba(255, 255, 255, 0.5);
}

/* 图表容器样式 */
.ai-chart-container {
  position: relative;
  width: 100%;
  height: 0; /* 初始高度为0，由图表内容决定 */
  padding-bottom: 75%; /* 16:9 比例 */
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f7fa;
  border: 1px solid #eaedf1;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.ai-chart {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.chart-error {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #f5222d;
  font-size: 14px;
  padding: 10px;
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 4px;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .chat-main.history-open {
    margin-right: 0;
    transform: translateX(-100%);
  }
  
  .chat-history {
    width: 100%;
  }
  
  .history-open .toggle-history-btn {
    right: 1.5rem;
  }
  
  .message-content {
    max-width: 90%;
  }
  
  .welcome-content {
    padding: 1.5rem;
  }
  
  .welcome-content h2 {
    font-size: 1.8rem;
  }
}

/* 新对话按钮样式 */
.new-chat-icon {
  position: absolute;
  top: 1.5rem;
  left: 1.5rem;
  width: 42px;
  height: 42px;
  border-radius: 50%;
  background-color: #1890ff;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(24, 144, 255, 0.25);
}

.new-chat-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.35);
  background-color: #40a9ff;
}

.new-chat-icon svg {
  width: 20px;
  height: 20px;
}

.new-chat-icon .tooltip {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.75);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  visibility: hidden;
  opacity: 0;
  transition: opacity 0.3s, visibility 0.3s;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 8px;
}

.new-chat-icon:hover .tooltip {
  visibility: visible;
  opacity: 1;
}
</style> 